import * as Paho from 'paho-mqtt'
import { ElMessage as message } from 'element-plus'
import { getMachineCode } from '@/utils/common'
let client = null

const socket = {
  methods: {
    connection({ location, port,  topics, onMessage }) {
      let Message = false;
      console.log("modules connecting", location, port,  topics)
      client = new Paho.Client(
        location,
        port,
        "",
        `mqttx_${getMachineCode()}`
        // "mqttx_303927b3",
      )
      client.connect({
        timeout: 15,
        keepAliveInterval:10,
        cleanSession: true,
        useSSL: false,
        userName:'user',
        password:'87YvoSR7@iHY78YOrl4',
        onSuccess: () => {
          message.success('连接成功!')
          Message = true;
          console.log("Message----", Message);
          console.log("[ mqtt ] == 连接成功");
          client.subscribe(topics);
          client.onMessageArrived = message => {
            onMessage(message.payloadString);
          };
          client.onConnectionLost = responseObject => {
            console.log("[ mqtt ] ==  responseObject ===========",responseObject)
            if (responseObject.errorCode !== 0) {
              message.info('连接断开!')
              console.log("[ mqtt ] == 连接断开，注意重连");
              Message = false;
            }
          };
        },
        onFailure: () => {
          message.info('连接失败，请查看网络!')
          console.log("[ mqtt ] == 连接失败，请查看网络");
          Message = false;
        }
      });
      console.log('返回Message-------', Message);
      return Message;
    },

    onMessageArrived({ sendata }) {
      let message = new Paho.Message(sendata); // 消息内容
      message.destinationName = "DataTest"; // 目标主题
      client.send(message); // 推送主题
    },
    disconnect() {
      if(client.isConnected()){
        client.disconnect();
        message.info('连接断开!')
        console.log("[ mqtt ] == 连接断开，注意重连");
        socket.state = false
      }
     
    }
  }
};
export default socket;
